package com.example.anr;

import android.os.Looper;
import android.os.MessageQueue;
import android.util.Printer;

import java.lang.reflect.Field;

public class ZYAnrManager implements Printer {

    private static final String TAG = "ZYAnrManager";
    private static int id = 0;

    private static final ZYAnrManager zyAnrManager = new ZYAnrManager();

    private ZYAnrManager() {
        monitor();

    }


    public static ZYAnrManager getInstance() {
        return zyAnrManager;
    }

    private void monitor() {
        monitorMsg();
        monitorIdleHandler();
    }


    //Msg monitor
    private void monitorMsg() {
        Looper.getMainLooper().setMessageLogging(this);
    }

    //IdleHandler monitor
    private void monitorIdleHandler() {
        try {
            MessageQueue mainQueue = Looper.getMainLooper().getQueue();
            Field field = MessageQueue.class.getDeclaredField("mIdleHandlers");
            field.setAccessible(true);
            MyArrayList<MessageQueue.IdleHandler> myIdleHandlerArrayList = new MyArrayList<>();
            field.set(mainQueue, myIdleHandlerArrayList);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    //IdleHandler nativePollOnce
    //1. input event
    private void monitorNativePollOnce() {

    }

    long start = 0;

    @Override
    public void println(String x) {
        if (x.startsWith(">>>>>")) {
            start = System.currentTimeMillis();
        } else if (x.startsWith("<<<<<")) {
            long end = System.currentTimeMillis();
            AnrLog.d(TAG, "MSG " + (id++) + " total(" + (end - start) + ")" + x);
        }
    }
}
